/**
 * 节拍器服务
 * 处理节拍器的核心功能
 */

// 导入base64编码的音频作为后备
import {
  clickAccent, clickNormal,
  woodBlockAccent, woodBlockNormal,
  drumAccent, drumNormal,
  electronicAccent, electronicNormal
} from './audioBase64.js';

// 节拍器类
class MetronomeService {
  constructor() {
    // 状态
    this.isPlaying = false;
    this.tempo = 60; // 默认速度改为60
    this.beats = 4;
    this.currentBeat = 0;
    this.accent = 1;
    this.volume = 1.0;
    this.soundType = 1; // 修改为木鱼声（索引1）
    this.vibrationEnabled = true;
    this.interval = 60000 / this.tempo;
    this.intervalId = null;
    this.onBeatCallback = null;
    this.useBase64Fallback = false; // 默认使用本地文件
    this.platform = '';
    
    // 获取平台信息
    try {
      const systemInfo = uni.getSystemInfoSync();
      this.platform = systemInfo.platform;
      console.log('当前平台:', this.platform);
    } catch (e) {
      console.error('获取系统信息失败:', e);
    }
    
    console.log('MetronomeService初始化完成 - 默认使用本地文件');
  }
  
  // 声音类型配置
  get soundTypes() {
    return [
      {
        name: '点击声',
        accent: '/static/sounds/click_accent.mp3',
        normal: '/static/sounds/click_normal.mp3',
        accentBase64: clickAccent,
        normalBase64: clickNormal
      },
      {
        name: '木鱼声',
        accent: '/static/sounds/woodblock_accent.mp3',
        normal: '/static/sounds/woodblock_normal.mp3',
        accentBase64: woodBlockAccent,
        normalBase64: woodBlockNormal
      },
      {
        name: '鼓声',
        accent: '/static/sounds/drum_accent.mp3',
        normal: '/static/sounds/drum_normal.mp3',
        accentBase64: drumAccent,
        normalBase64: drumNormal
      },
      {
        name: '电子声',
        accent: '/static/sounds/electronic_accent.mp3',
        normal: '/static/sounds/electronic_normal.mp3',
        accentBase64: electronicAccent,
        normalBase64: electronicNormal
      }
    ];
  }

  // 强制设置音频源类型
  setAudioSourceType(useBase64 = false) {
    this.useBase64Fallback = false; // 始终使用本地文件
    console.log('设置已更新：只使用本地文件');
    return this.useBase64Fallback;
  }
  
  // 测试本地文件是否可访问
  testLocalFiles() {
    return new Promise((resolve) => {
      try {
        const testAudio = uni.createInnerAudioContext();
        
        // 测试音频文件路径 - 使用木鱼声路径
        const testPath = this.soundTypes[1].accent; // 木鱼声强拍
        
        testAudio.src = testPath;
        console.log('测试本地音频路径:', testPath);
        
        let isResolved = false;
        
        testAudio.onError((err) => {
          if (!isResolved) {
            console.log('本地音频文件无法访问', err);
            isResolved = true;
            testAudio.destroy();
            resolve(false);
          }
        });
        
        testAudio.onCanplay(() => {
          if (!isResolved) {
            console.log('本地音频文件可以访问');
            isResolved = true;
            testAudio.destroy();
            resolve(true);
          }
        });
        
        // 添加超时处理
        setTimeout(() => {
          if (!isResolved) {
            console.log('测试本地音频超时');
            isResolved = true;
            testAudio.destroy();
            resolve(false);
          }
        }, 3000);
      } catch (error) {
        console.error('测试本地音频时出错:', error);
        resolve(false);
      }
    });
  }
  
  // 播放声音
  playSound(isAccent) {
    try {
      // 创建新的音频上下文
      const audio = uni.createInnerAudioContext();

      // 选择正确的声音类型
      const soundType = this.soundTypes[this.soundType];
      
      // 使用本地音频文件
      const path = isAccent ? soundType.accent : soundType.normal;
      audio.src = path;
      console.log(`播放本地音频: ${path}, 名称: ${soundType.name}`);
      
      // 设置音量
      audio.volume = this.volume;
      
      // 注册事件处理器
      audio.onPlay(() => {
        console.log('音频开始播放');
      });
      
      audio.onEnded(() => {
        console.log('音频播放完成');
        audio.destroy();
      });
      
      // 错误处理
      audio.onError((res) => {
        // 防止res未定义
        const errCode = res && res.errCode ? res.errCode : '未知';
        const errMsg = res && res.errMsg ? res.errMsg : '未知错误';
        console.error(`音频播放错误 [${errCode}]: ${errMsg}, 源: ${audio.src}`);
        
        // 尝试备用方法
        this.triggerVibration(isAccent);
      });
      
      // 播放
      audio.play();
      
      // 同时提供振动反馈 (如果启用)
      if (this.vibrationEnabled) {
        this.triggerVibration(isAccent);
      }
      
      return true;
    } catch (error) {
      console.error('播放声音时出错:', error);
      // 出错时使用振动
      this.triggerVibration(isAccent);
      return false;
    }
  }
  
  // 振动触发
  triggerVibration(isAccent) {
    try {
      if (typeof uni !== 'undefined') {
        // 强拍使用长振动，弱拍使用短振动
        if (isAccent) {
          // 强拍 - 使用强振动
          uni.vibrateLong({
            success: () => console.log('强拍振动成功'),
            fail: (err) => console.error('强拍振动失败:', err)
          });
        } else {
          // 弱拍 - 使用弱振动
          uni.vibrateShort({
            success: () => console.log('弱拍振动成功'),
            fail: (err) => console.error('弱拍振动失败:', err)
          });
        }
      }
    } catch (error) {
      console.error('振动触发失败:', error);
    }
  }

  // 开始播放
  start() {
    if (this.isPlaying) return;
    
    this.isPlaying = true;
    this.currentBeat = 0;
    
    // 第一拍立即播放
    this.tick();
    
    // 设置定时器
    this.intervalId = setInterval(() => {
      this.tick();
    }, this.interval);
    
    console.log(`节拍器开始: ${this.tempo} BPM, ${this.beats} 拍`);
  }
  
  // 停止播放
  stop() {
    if (!this.isPlaying) return;
    
    this.isPlaying = false;
    clearInterval(this.intervalId);
    this.intervalId = null;
    
    console.log('节拍器停止');
  }
  
  // 节拍更新
  tick() {
    this.currentBeat++;
    if (this.currentBeat > this.beats) {
      this.currentBeat = 1;
    }
    
    // 确定是否是强拍
    const isAccent = this.currentBeat === this.accent;
    
    // 播放声音
    this.playSound(isAccent);
    
    // 回调函数
    if (this.onBeatCallback) {
      this.onBeatCallback(this.currentBeat, isAccent);
    }
  }
  
  // 设置速度
  setTempo(bpm) {
    if (bpm < 30) bpm = 30;
    if (bpm > 240) bpm = 240;
    
    this.tempo = bpm;
    this.interval = 60000 / this.tempo;
    
    // 如果正在播放，需要重置定时器
    if (this.isPlaying) {
      clearInterval(this.intervalId);
      this.intervalId = setInterval(() => {
        this.tick();
      }, this.interval);
    }
  }
  
  // 设置节拍器
  setTimeSignature(beatsPerMeasure, accentBeat = 1) {
    this.beats = beatsPerMeasure;
    this.accent = accentBeat;
    
    if (this.currentBeat > this.beats) {
      this.currentBeat = 0;
    }
  }
  
  // 设置音量
  setVolume(level) {
    if (level < 0) level = 0;
    if (level > 1) level = 1;
    
    this.volume = level;
  }
  
  // 设置声音类型
  setSoundType(index) {
    if (index >= 0 && index < this.soundTypes.length) {
      this.soundType = index;
    }
  }
  
  // 设置振动
  setVibration(enabled) {
    this.vibrationEnabled = enabled;
  }
  
  // 设置回调函数
  setOnBeatCallback(callback) {
    if (typeof callback === 'function') {
      this.onBeatCallback = callback;
    }
  }
  
  // 检测是否支持振动
  supportsVibration() {
    return typeof uni !== 'undefined' && uni.vibrateShort;
  }
  
  // 检测是否支持背景播放
  supportsBackgroundPlayback() {
    return typeof uni !== 'undefined' && uni.getBackgroundAudioManager;
  }
  
  // 测试音频
  testAudio(soundTypeIndex, isAccent) {
    try {
      console.log(`测试音频: 类型=${soundTypeIndex}, 强拍=${isAccent}`);
      
      const oldType = this.soundType;
      this.soundType = soundTypeIndex;
      const result = this.playSound(isAccent);
      this.soundType = oldType;
      return result;
    } catch (error) {
      console.error('测试音频失败:', error);
      return false;
    }
  }
}

// 创建单例
const metronomeService = new MetronomeService();

export default metronomeService; 